//
//  BDHomeDetailViewController.m
//  BadBoy
//
//  Created by wen on 2017/3/20.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDHomeDetailViewController.h"
#import "BDHomeTableViewCell.h"
#import "BDHomeDetailInfoTableViewCell.h"
#import "BDHomeDetailPinglunTableViewCell.h"
#import "BDUserModel.h"
#import "BDHomeDetailCommentsModel.h"
#import "BDHomeCommentViewController.h"
#import "BDForwardViewController.h"
#import "PopoverView.h"
#import "PBViewController.h"
#import "CallExternalProcessBehavior.h"
#import <UMSocialCore/UMSocialCore.h>
#import <UShareUI/UShareUI.h>
#import "BDUserInfoViewController.h"
#import "BDVipPayView.h"
#import "AppDelegate.h"
#import "BDVIPViewController.h"
#import "BDPayViewController.h"

@interface BDHomeDetailViewController ()<UITableViewDelegate, UITableViewDataSource, PBViewControllerDelegate, PBViewControllerDataSource>
{
    NSArray *showImagesArray;
    UIButton *seletedButton;
    UIView *curClickView;
    BOOL haveShopInfo;
}

@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) NSMutableArray *datasource;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIButton *zanButton;
@property (nonatomic, strong) UIButton *messageButton;
@property (nonatomic, strong) UIButton *ForwardButton;      //转发按钮
@property (nonatomic, strong) UIButton *shareButton;        //分享按钮

//@property (nonatomic, strong) NSMutableArray *addressDatasource;
@end

@implementation BDHomeDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = ASLocalizedString(@"详细内容");
    
    [self addSubviews];
    [self bindRAC];
    
    [self requestDatasource];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)addSubviews{
    [self.view addSubview:self.bottomView];
}

- (void)bindRAC{
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"addPostCommentSuccess" object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        [self.datasource removeLastObject];
        self.startPage = @"1";
        [self requestComments];
    }];
    
    [[self.zanButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [BDUserModel judgeCurrentUserWithNormalBlock:^{
            if (self.zanButton.selected == YES) {
                return ;
            }
            NSString *url = [NSString stringWithFormat:@"%@post/%@/praise", KBDBaseURL, @(self.homeModel.my_id)];
            NSDictionary *para = @{@"id":@(self.homeModel.my_id)};
            NSString *headValid = [BDUserModel getHeaderValidation];
            RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
            
            [signal subscribeNext:^(id  _Nullable x) {
                self.zanButton.selected = YES;
                self.homeModel.praiseCount++;
                self.homeModel.praise = YES;
                [self.tableview reloadData];
            }];
            [signal subscribeError:^(NSError * _Nullable error) {
                [MBManager showBriefAlert:ASLocalizedString(@"点赞失败")clickHidden:NO clickBlock:nil];
            }];
        }];
    }];
    [[self.ForwardButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [BDUserModel judgeCurrentUserWithNormalBlock:^{
            BDForwardViewController *forwardVC = [[BDForwardViewController alloc] init];
            forwardVC.homeModel = self.homeModel;
            [self.navigationController pushViewController:forwardVC animated:YES];
        }];
        
    }];
    [[self.messageButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [BDUserModel judgeCurrentUserWithNormalBlock:^{
            BDHomeCommentViewController *commntVC = [[BDHomeCommentViewController alloc] init];
            commntVC.post_id = self.homeModel.my_id;
            commntVC.title = [NSString stringWithFormat:ASLocalizedString(@"回复 %@"), self.homeModel.user.nickname];
            [self.navigationController pushViewController:commntVC animated:YES];
        }];
        
    }];
    [[self.shareButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [BDUserModel judgeCurrentUserWithNormalBlock:^{
            [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine),@(UMSocialPlatformType_WechatFavorite)]];
            [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
                // 根据获取的platformType确定所选平台进行下一步操作
                NSString *url = [NSString stringWithFormat:@"%@tool/shareData", KBDBaseURL];
                NSString *headValid = [BDUserModel getHeaderValidation];
                RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
                
                [signal subscribeNext:^(id  _Nullable x) {
                    //创建分享消息对象
                    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
                    
                    //创建网页内容对象
                    NSString *thumbURL = x[@"share_logo"];
                    NSString *title = x[@"share_title"];
                    NSString *descr = x[@"share_text"];
                    NSString *webUrl = x[@"share_url"];
                    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title
                                                                                             descr:descr
                                                                                         thumImage:thumbURL];
                    //设置网页地址
                    shareObject.webpageUrl = webUrl;
                    
                    //分享消息对象设置分享内容对象
                    messageObject.shareObject = shareObject;
                    
                    //调用分享接口
                    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
                        if (error) {
                            UMSocialLogInfo(@"************Share fail with error %@*********",error);
                        }else{
                            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                                //                            UMSocialShareResponse *resp = data;
                                //                            //分享结果消息
                                //                            UMSocialLogInfo(@"response message is %@",resp.message);
                                //                            //第三方原始返回的数据
                                //                            UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                                //                            NSLog(ASLocalizedString(@"分享成功了"));
                                NSString *backUrl = [NSString stringWithFormat:@"%@post/%@/shared", KBDBaseURL, @(self.homeModel.my_id)];
                                RACSignal *backSignal = [[BDNetworkingServer yy_POST:backUrl parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
                                [backSignal subscribeNext:^(id  _Nullable x) {
                                    self.homeModel.sharedCount++;
                                    //                                [self.tableView reloadData];
                                    [MBManager showBriefAlert:ASLocalizedString(@"分享成功")clickHidden:NO clickBlock:nil];
                                }];
                                [backSignal subscribeError:^(NSError * _Nullable error) {
                                    [MBManager showBriefAlert:ASLocalizedString(@"分享失败")clickHidden:NO clickBlock:nil];
                                }];
                            }else{
                                //                            UMSocialLogInfo(@"response data is %@",data);
                                [MBManager showBriefAlert:ASLocalizedString(@"分享失败")clickHidden:NO clickBlock:nil];
                            }
                        }
                    }];
                }];
                [signal subscribeError:^(NSError * _Nullable error) {
                    [MBManager showBriefAlert:ASLocalizedString(@"获取分享信息失败")clickHidden:NO clickBlock:nil];
                }];
            }];
        }];
    }];
}

- (void)requestDatasource{
    NSString *url = nil;
    if (self.homeModel == nil) {
        url = [NSString stringWithFormat:@"%@post/%@", KBDBaseURL, @(self.post_id)];
    }else{
        url = [NSString stringWithFormat:@"%@post/%@", KBDBaseURL, @(self.homeModel.my_id)];
    }
    
    NSString *headValid = [BDUserModel getHeaderValidation];
    RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        if (self.homeModel == nil) {
            self.homeModel = [BDHomeModel mj_objectWithKeyValues:x];
        }else {
            BDHomeModel *newHomeModel = [BDHomeModel mj_objectWithKeyValues:x];
            self.homeModel.is_public = newHomeModel.is_public;
            self.homeModel.status = newHomeModel.status;
        }
        self.homeModel.isDetail = YES;
        self.zanButton.selected = self.homeModel.praise;
        [self sortingDatasource];
    }];
    [signal subscribeError:^(NSError * _Nullable error) {
        [self showErrorViewWithTapBlock:^{
            
        }];
    }];
}

- (void)sortingDatasource{
    
    self.datasource = [NSMutableArray array];
    
    if (self.homeModel.haveMeracten == YES && self.homeModel.isPurchase == NO && self.homeModel.price != 0) {
        [self requestComments];
    }else {
        NSMutableArray *addArray = [NSMutableArray array];
        
        BDHomeModel *curModel = self.homeModel;
        
        if (self.homeModel.repost != nil) {
            curModel = self.homeModel.repost;
        }
        
        if ([curModel.shop isNotEmpty]) {
            [addArray addObject:@{@"identifier":@"shopname", @"image":@"dianpu", @"title":curModel.shop, @"needRight":@NO}];
        }
        if ([curModel.address isNotEmpty]) {
            [addArray addObject:@{@"identifier":@"address", @"image":@"dizhi", @"title":curModel.address, @"needRight":@YES}];
        }
        if ([curModel.contact isNotEmpty]) {
            [addArray addObject:@{@"identifier":@"contact", @"image":@"phone", @"title":curModel.contact, @"needRight":@YES}];
        }
        if ([curModel.consumption isNotBlank]) {
            [addArray addObject:@{@"identifier":@"consumption", @"image":@"xiaofei", @"title":@"消费价格", @"subTitle":[NSString stringWithFormat:@"¥%@", curModel.consumption], @"needRight":@NO}];
        }
        if ([curModel.consumed_at isNotBlank]) {
            [addArray addObject:@{@"identifier":@"consumed_at", @"image":@"time", @"title":@"消费时间", @"subTitle":curModel.consumed_at, @"needRight":@NO}];
        }
        
        if (addArray.count != 0) {
            [self.datasource addObject:addArray];
            haveShopInfo = YES;
        }else{
            haveShopInfo = NO;
        }
        [self requestComments];
    }
}

- (void)requestComments{
    NSString *url = [NSString stringWithFormat:@"%@post/%ld/comments?page=%@&size=%@", KBDBaseURL, (long)self.homeModel.my_id, self.startPage, self.pageSize];
    NSString *headerValid = [BDUserModel getHeaderValidation];
    
    RACCommand *command = [BDNetworkingServer yy_GET:url parameters:nil validation:headerValid automaticProcessingError:YES];
    RACSignal *signal= [command execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        self.isEnd = [x[@"is_end"] boolValue];
        self.startPage = x[@"next_page"];
        NSMutableArray *commentArray = [BDHomeDetailCommentsModel mj_objectArrayWithKeyValuesArray:x[@"list"]];

        if (self.datasource.count == haveShopInfo + 1) {
            NSMutableArray *dataComAr = self.datasource.lastObject;
            [dataComAr addObjectsFromArray:commentArray];
        }else{
            [self.datasource addObject:commentArray];
        }
        [self.tableview reloadData];
        NSArray *comArr = self.datasource.lastObject;
        if (comArr.count != 0) {
            [self setTableiewFooterViewStateFor:self.tableview datasourceCount:comArr.count];
        }
    }];
    [signal subscribeNext:^(id  _Nullable x) {
        
    }];
}

#pragma mark ------------------------PBViewController代理---------------------------
- (NSInteger)numberOfPagesInViewController:(PBViewController *)viewController {
    return showImagesArray.count;
}

- (void)viewController:(PBViewController *)viewController presentImageView:(UIImageView *)imageView forPageAtIndex:(NSInteger)index progressHandler:(void (^)(NSInteger, NSInteger))progressHandler {
    
    UIImage *placeholder = [UIImage imageNamed:@"business_pic"];
    [imageView sd_setImageWithURL:[NSURL URLWithString:showImagesArray[index]]
                 placeholderImage:placeholder
                          options:0
                         progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                             
                         } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                             
                         }];
}

- (UIView *)thumbViewForPageAtIndex:(NSInteger)index {
    return curClickView;
}

- (void)viewController:(PBViewController *)viewController didSingleTapedPageAtIndex:(NSInteger)index presentedImage:(UIImage *)presentedImage {
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.datasource.count + 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else {
        return [self.datasource[section - 1] count];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return self.homeModel.cellHeight;
    }else if (indexPath.section == self.datasource.count) {
        BDHomeDetailCommentsModel *comment = self.datasource[indexPath.section - 1][indexPath.row];
        return comment.cellHeigth;
    }else{
        return 40;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == self.datasource.count) {
        return 45;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == self.datasource.count) {
        UIView *headView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
        if (headView == nil) {
            headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 45)];
            
            UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 35)];
            contentView.bottom = headView.height;
            contentView.backgroundColor = [UIColor whiteColor];
            [headView addSubview:contentView];
            
            CGFloat btnWidth = 60;
            NSArray *titleArray = @[[NSString stringWithFormat:ASLocalizedString(@"评论 %zd"), self.homeModel.commentCount],
                                    [NSString stringWithFormat:ASLocalizedString(@"赞 %zd"), self.homeModel.praiseCount]];
            
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, btnWidth, 2)];
            lineView.backgroundColor = [UIColor colorWithHexString:@"4d7aad"];
            lineView.bottom = contentView.height;
            lineView.left = 10;
            [contentView addSubview:lineView];
            
            for (int i = 0; i < 1 ; i++) {
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                button.size = CGSizeMake(btnWidth, 35);
                if (i == 1) {
                    button.right = kBDScreenWidth - 10;
                }else{
                    button.left = 10 + btnWidth * i;
                }
                button.tag = 4422 + i;
                [button setTitle:titleArray[i] forState:UIControlStateNormal];
                button.titleLabel.font = [UIFont systemFontOfSize:12];
                [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [contentView addSubview:button];
                if (i == 0) {
                    seletedButton = button;
                }
                [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                    if (button == seletedButton) {
                        return ;
                    }else{
                        [UIView animateWithDuration:0.3 animations:^{
                            lineView.left = button.left;
                        } completion:^(BOOL finished) {
                            seletedButton = button;
                        }];
                    }
                }];

            }
        }
        return headView;
    }else{
        UIView *headView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"emptyHeader"];
        if (headView ==nil) {
            headView= [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, [self tableView:tableView heightForHeaderInSection:section])];
            headView.backgroundColor = [UIColor clearColor];
        }
        return headView;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        BDHomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mainCell" forIndexPath:indexPath];
        [cell configeWithModel:self.homeModel avatarBlock:^{
            
        } allButtonBlock:nil zanBlock:nil forwardBlock:nil pinglunBlock:nil sharedBlock:nil merchantsBlock:^{
            BOOL isControl = [[[NSUserDefaults standardUserDefaults] objectForKey:@"versionControl"] boolValue];
            BDUserModel *currentUser = [BDUserModel getCurrentUser];
            
            if (isControl == YES || currentUser.is_auth == NO){
                [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"购买会员可以查看所有加密帖子，是否前往购买？")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"取消")otherTitle:@[ASLocalizedString(@"好的")] clickBlock:^(NSInteger index) {
                    if (index == 1) {
                        BDVIPViewController *vipVC = [[BDVIPViewController alloc] init];
                        [self.navigationController pushViewController:vipVC animated:YES];
                    }
                }];
            }else{
                BDPayViewController *payVC = [[BDPayViewController alloc] initWithPaySuccessedBlock:^{
                    [MBManager showBriefAlert:ASLocalizedString(@"支付成功")clickHidden:NO clickBlock:nil];
                    self.homeModel.purchase = @[@""];
                    [self sortingDatasource];
                }];
                payVC.productId = [NSString stringWithFormat:@"%@", @(self.homeModel.my_id)];
                payVC.price = [NSDecimalNumber decimalNumberWithDecimal:[@(self.homeModel.price) decimalValue]];
                payVC.payType = BDPayTypePost;
                payVC.product = self.homeModel;
                payVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:payVC animated:YES];
                
                
//                BDVipPayView *payView = [BDVipPayView showWithProductId:self.homeModel.price != 0 ? self.homeModel.my_id : self.homeModel.repost.my_id type:BDPayTypePost title:ASLocalizedString(@"购买主题")product:[NSString stringWithFormat:ASLocalizedString(@"%@的主题"), self.homeModel.repost == nil ? self.homeModel.user.nickname : self.homeModel.repost.user.nickname] price:[NSString stringWithFormat:ASLocalizedString(@"%@ 元"), @(self.homeModel.price != 0 ? self.homeModel.price : self.homeModel.repost.price)] addressArray:nil];
//                __weak AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//                app.payResultBlock = ^(int state) {
//                    // BDLog(ASLocalizedString(@"支付会调用这个回调回到这个页面"));
//                    app.payResultBlock = nil;
//                    [payView hidden];
//                    if (state == 1) {
//                        [MBManager showBriefAlert:ASLocalizedString(@"支付成功")clickHidden:NO clickBlock:nil];
//                        if (self.homeModel.price != 0) {
//                            self.homeModel.purchase = @[@""];
//                        }else{
//                            self.homeModel.repost_purchase = @[@""];
//                        }
//                        [self sortingDatasource];
//                    }else if (state == 2) {
//                        [MBManager showBriefAlert:ASLocalizedString(@"支付失败")clickHidden:YES clickBlock:nil];
//                    }else if (state == 3) {
//                        [MBManager showBriefAlert:ASLocalizedString(@"支付取消")clickHidden:YES clickBlock:nil];
//                    }
//                };
            }
        } imageClickBlock:^(NSInteger index, NSArray *imagesArray, UIView *clickView) {
            showImagesArray = imagesArray;
            PBViewController *pbViewController = [PBViewController new];
            pbViewController.pb_dataSource = self;
            pbViewController.pb_delegate = self;
            pbViewController.pb_startPage = index;
            curClickView = clickView;
            [self presentViewController:pbViewController animated:YES completion:nil];
        }];
        return cell;
    }else if (indexPath.section == self.datasource.count) {
        BDHomeDetailPinglunTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pinglunCell"];
        if (!cell) {
            cell = [[BDHomeDetailPinglunTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"pinglunCell"];
        }
        NSMutableArray *curDa = self.datasource.lastObject;
        BDHomeDetailCommentsModel *commentModel = curDa[indexPath.row];
        BDUserModel *curUser = [[BDUserModel alloc] init];
        curUser.nickname = commentModel.user.nickname;
        curUser.user_id = commentModel.user.user_id;
        curUser.cover = commentModel.user.cover;
        curUser.vip_level = commentModel.user.vip_level;
        if (indexPath.row == 0) {
            cell.isFirst = YES;
        }else{
            cell.isFirst = NO;
        }
        __weak BDHomeDetailViewController *weakSelf = self;
        [cell configeWithModel:commentModel avatarClickBlock:^{
            BDUserInfoViewController *userVC = [[BDUserInfoViewController alloc] initWithUserID:curUser.user_id isFollow:NO guanzhuBlock:nil];
            [weakSelf.navigationController pushViewController:userVC animated:YES];
        } replayBlock:^{
            [BDUserModel judgeCurrentUserWithNormalBlock:^{
                BDHomeCommentViewController *commntVC = [[BDHomeCommentViewController alloc] init];
                commntVC.post_id = weakSelf.homeModel.my_id;
                commntVC.title = [NSString stringWithFormat:ASLocalizedString(@"回复 %@"), commentModel.user.nickname];
                commntVC.comment_id = commentModel.my_id;
                [weakSelf.navigationController pushViewController:commntVC animated:YES];
            }];
        } replayUserClick:^(NSInteger user_id) {
            BDUserInfoViewController *userVC = [[BDUserInfoViewController alloc] initWithUserID:user_id isFollow:NO guanzhuBlock:nil];
            [weakSelf.navigationController pushViewController:userVC animated:YES];
        } replayContrntClick:^(NSString *userName, NSInteger user_id) {
            [BDUserModel judgeCurrentUserWithNormalBlock:^{
                BDHomeCommentViewController *commntVC = [[BDHomeCommentViewController alloc] init];
                commntVC.post_id = weakSelf.homeModel.my_id;
                commntVC.title = [NSString stringWithFormat:ASLocalizedString(@"回复 %@"), userName];
                commntVC.comment_id = commentModel.my_id;
                commntVC.reply_user_id = user_id;
                [weakSelf.navigationController pushViewController:commntVC animated:YES];
            }];
        }];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        NSDictionary *dic = self.datasource[0][indexPath.row];
        BDHomeDetailInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"infoCell" forIndexPath:indexPath];
        if (indexPath.row == 0) {
            cell.isFirst = YES;
        }else{
            cell.isFirst = NO;
        }
        cell.imageView.image = [UIImage imageNamed:dic[@"image"]];
        cell.textLabel.text = dic[@"title"];
        if (dic[@"subTitle"]) {
            cell.detailTextLabel.text = dic[@"subTitle"];
        }else{
            cell.detailTextLabel.text = nil;
        }
        if ([dic[@"needRight"] boolValue]) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }else{
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == self.datasource.count) {
        NSArray *lastArr = self.datasource.lastObject;
        if (lastArr.count == 0){
            return 80;
        }
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == self.datasource.count) {
        NSArray *lastArr = self.datasource.lastObject;
        if (lastArr.count == 0) {
            NSString *labelString = seletedButton.tag - 4422 ? ASLocalizedString(@"还没有赞，送出第一个赞吧~"): ASLocalizedString(@"还没有评论，上传第一条评论吧~");
            NSString *buttonString = seletedButton.tag - 4422 ? ASLocalizedString(@"赞"): ASLocalizedString(@"评论");
            UIView *empyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 80)];
            empyView.backgroundColor = [UIColor whiteColor];
            UILabel *label = [[UILabel alloc] init];
            label.text = labelString;
            [label sizeToFit];
            label.top = 15;
            label.centerX = kBDScreenWidth / 2.0;
            label.textColor = [UIColor colorWithHexString:@"#767676"];
            label.font = [UIFont systemFontOfSize:13];
            [empyView addSubview:label];
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.size = CGSizeMake(80, 27);
            [button setTitle:buttonString forState:UIControlStateNormal];
            button.backgroundColor = KBDColorBlue;
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            button.layer.masksToBounds = YES;
            button.layer.cornerRadius = 4;
            button.titleLabel.font = [UIFont systemFontOfSize:14];
            button.top = label.bottom + 10;
            button.centerX = label.centerX;
            [empyView addSubview:button];
            
            [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                if ([buttonString isEqualToString:ASLocalizedString(@"评论")]) {
                    [self.messageButton sendActionsForControlEvents:UIControlEventTouchUpInside];
                }else{
                    [self.zanButton sendActionsForControlEvents:UIControlEventTouchUpInside];
                }
            }];
            return empyView;
        }
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1 && self.datasource.count == 2) {
        NSDictionary *dic = self.datasource[0][indexPath.row];
        if ([dic[@"identifier"] isEqualToString:@"contact"]) {
//            [CallExternalProcessBehavior phoneWithPhoneNumber:self.homeModel.contact];
        }else if ([dic[@"identifier"] isEqualToString:@"address"]) {
            [CallExternalProcessBehavior routeNavigationWithLongitue:self.homeModel.longitude.doubleValue latitue:self.homeModel.latitude.doubleValue];
        }
    }
}

- (UIView *)bottomView{
    if (!_bottomView) {
        self.bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kBDScreenWidth, kBDButtonHeight)];
        _bottomView.bottom = kBDScreenHeight;
        _bottomView.backgroundColor = [UIColor colorWithRed:54/255.0 green:54/255.0 blue:54/255.0 alpha:1.0f];
        [_bottomView addSubview:self.zanButton];
        [_bottomView addSubview:self.ForwardButton];
        [_bottomView addSubview:self.messageButton];
        [_bottomView addSubview:self.shareButton];
        
        NSArray *buttonArr = @[self.zanButton, self.messageButton, self.ForwardButton,  self.shareButton];
        
        for (int i = 0; i < buttonArr.count; i++) {
            UIButton *button = buttonArr[i];
            button.frame = CGRectMake(kBDScreenWidth / 4.0 * i, 0, kBDScreenWidth / 4.0, _bottomView.height);
            
            if (i > 0) {
                UIView *line = [[UIView alloc] initWithFrame:CGRectMake(kBDScreenWidth / 4.0 * i, 0, 1, 20)];
                line.centerY = _bottomView.height / 2.0;
                line.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.2];
                [_bottomView addSubview:line];
            }
        }
    }
    return _bottomView;
}

-(UIButton *)zanButton{
    if (!_zanButton) {
        _zanButton = [[UIButton alloc]init];
        [_zanButton setImage:[UIImage imageNamed:@"zan-2"] forState:UIControlStateNormal];
        [_zanButton setImage:[UIImage imageNamed:@"zan_sel"] forState:UIControlStateSelected];
        [_zanButton setTitle:ASLocalizedString(@"赞")forState:UIControlStateNormal];
        _zanButton.imageEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 5);
        _zanButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, -5);
        [_zanButton setTitleColor:kBDTimeColor forState:UIControlStateNormal];
        _zanButton.titleLabel.font = [UIFont systemFontOfSize:14];
    }
    return _zanButton;
}

-(UIButton *)ForwardButton{
    if (!_ForwardButton) {
        _ForwardButton = [[UIButton alloc]init];
        [_ForwardButton setImage:[UIImage imageNamed:@"zhuanfa-2"] forState:UIControlStateNormal];
        [_ForwardButton setTitle:ASLocalizedString(@"转发")forState:UIControlStateNormal];
        _ForwardButton.imageEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 5);
        _ForwardButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, -5);
        [_ForwardButton setTitleColor:kBDTimeColor forState:UIControlStateNormal];
        _ForwardButton.titleLabel.font = [UIFont systemFontOfSize:14];
    }
    return _ForwardButton;
}

-(UIButton *)messageButton{
    if (!_messageButton) {
        _messageButton = [[UIButton alloc]init];
        [_messageButton setImage:[UIImage imageNamed:@"pinglun-2"] forState:UIControlStateNormal];
        [_messageButton setTitle:ASLocalizedString(@"评论")forState:UIControlStateNormal];
        _messageButton.imageEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 5);
        _messageButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, -5);
        [_messageButton setTitleColor:kBDTimeColor forState:UIControlStateNormal];
        _messageButton.titleLabel.font = [UIFont systemFontOfSize:14];
    }
    return _messageButton;
}

-(UIButton *)shareButton{
    if (!_shareButton) {
        _shareButton = [[UIButton alloc]init];
        [_shareButton setImage:[UIImage imageNamed:@"fengxiang-2"] forState:UIControlStateNormal];
        [_shareButton setTitle:ASLocalizedString(@"分享")forState:UIControlStateNormal];
        _shareButton.imageEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 5);
        _shareButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, -5);
        [_shareButton setTitleColor:kBDTimeColor forState:UIControlStateNormal];
        _shareButton.titleLabel.font = [UIFont systemFontOfSize:14];
    }
    return _shareButton;
}

- (UITableView *)tableview{
    if (!_tableview) {
        UITableViewController* tvc=[[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
        [self addChildViewController:tvc];
        [tvc.view setFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight - kBDTabBarHeight)];
        self.tableview = tvc.tableView;
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.sectionFooterHeight = 0;
        _tableview.backgroundColor = [UIColor clearColor];
        [_tableview registerClass:[BDHomeTableViewCell class] forCellReuseIdentifier:@"mainCell"];
        [_tableview registerClass:[BDHomeDetailInfoTableViewCell class] forCellReuseIdentifier:@"infoCell"];
        [_tableview registerClass:[BDHomeDetailPinglunTableViewCell class] forCellReuseIdentifier:@"pinglunCell"];
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableview];
    }
    return _tableview;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
